#!/usr/bin/python3
#-*- coding=utf-8 -*-

import os
import yaml
import argparse
import subprocess
import mysql.connector

CONFIG_FILE = "import_player.yaml"

def get_config(file_name):
    """
    解析yaml
    :file_name: 配置文件名
    :returns: setting dict

    """

    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        ins = None
        try:
            ins = yaml.load(f, Loader=yaml.FullLoader) #高版本
        except Exception as e:
            ins = yaml.load(f)
        return ins

def tencent_version(result, file_info, players):
    with open(file_info.get('name'), 'wb') as f:
        f.write(file_info.get('head', '').encode(encoding='UTF-8', errors='strict') + '\n')
        for player in players:
            for table in result:
                f.write("{0}  {2}  roleID='{1}'\n".format(player.get('server'), player.get('roleID'), table[0]))
            f.write('\n\n')


def foreign_version(result, conn_info, file_info, players):
    for player in players:
        cmd_str = "{} -h {} -P{} -u{} -p{} {} {} --where=\"{}\" --skip-lock-tables --skip-add-drop-table  --replace -t --skip-add-locks".format('mysqldump', conn_info.get('host'), conn_info.get('port'), conn_info.get('user'), conn_info.get('password'), conn_info.get('database'), '{}', "roleID='{}'".format(player.get('roleID')))
        with open(file_info.get('sql'), 'wb') as f:
            for table in result:
                cmd_str.format(table[0])
                print(cmd_str)
                # status, output = subprocess.getstatusoutput(cmd_str)
                # output = subprocess.check_output(cmd_str)
                # if status != 0:
                    # raise Exception("table:{} execute cmd:{} error:{}".format(table[0], cmd_str, output))
                # f.write(output)


def main():
    config = get_config(os.path.join(os.path.dirname(__file__), CONFIG_FILE))
    setting = config.get('setting', {})
    db = setting.get('db', {})
    remote_choice = db.get('remote_choice')
    conn_info = db.get('connector', [])
    conn_info = conn_info[remote_choice]
    players = setting.get('players', {})
    file_info = setting.get('file', {})

    conn = mysql.connector.connect(
        host = conn_info.get('host'),
        user = conn_info.get('user'),
        passwd = conn_info.get('password'),
        port = conn_info.get('port'),
        database = db.get('database')
    )
    sql_str = "select table_name from information_schema.columns where table_schema = '{0}' and column_name = '{1}'".format(db.get('database'), db.get('column'))
    cursor = conn.cursor()
    cursor.execute(sql_str)
    result = cursor.fetchall()

    if remote_choice == 2 or remote_choice == 3:
        foreign_version(result, conn_info, file_info, players)
    else:
        tencent_version(result, file_info, players)

    print("Successfull! it's you turn now!")

if __name__ == "__main__":
    main()
